<?php

namespace App\Http\Controllers\Admin;

use App\Models\Agency;
use App\Models\Area;
use App\Models\Kind;
use App\Models\Type;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 分类管理
 * Class AgencyController
 * @package App\Http\Controllers\Admin
 */
class AgencyController extends BaseController
{
    /**
     * 分类列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $list = Agency::orderBy("id", "desc")->paginate(config('site.other.paginate'));
        return backendView('agency.index', compact('list'));
    }

    /**
     * 新增分类
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {

            $this->validate($request, [
                'name' => 'required|max:255',
                'type_id' => 'required|exists:types,id',
                'province_id'=>'required|exists:areas,id',
                'registered_at' => 'required',

                'username' => 'required|unique:admins|min:4|max:20|only_alpha_dash',
                'password' => 'required|confirmed',

            ], [], [
                'name' => __("Name"),
                'type_id' => '机构类型',
                'province_id'=>__("Address"),
                'registered_at' => '注册时间',

                'username' => __('Account'),
                'password' => __('Password'),
                'password_confirmation' => __('Confirm Password'),

            ]);

            $data = $request->only(['name', 'type_id', 'province_id', 'registered_at', 'username', 'password']);
            $data['province'] = Area::where('id', $data['province_id'])->value("name");
            if (Agency::add($data)) {
                return redirect()->route('admin.agency.index')->with('success', __('Create success'));
            }

            return back()->with('error', __('Create failed'))->withInput();
        } else {
            $types = Type::where('status', 1)->get();
            $provinces = Area::where("parent_id", 0)->get();
            //dd($type);
            return backendView('agency.add', compact('types', 'provinces'));
        }
    }

    /**
     * 编辑分类
     * @param Request $request
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function edit(Request $request, $id = null)
    {
        /**
         * @var $agency Agency
         */
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod('POST')) {

            $this->validate($request, [
                'name' => 'required|max:255',
                'type_id' => 'required|exists:types,id',
                'province_id'=>'required|exists:areas,id',
                'registered_at' => 'required|date',

                'password' => 'nullable|confirmed',
            ], [], [
                'name' => '机构名称',
                'type_id' => '机构类型',
                'province_id'=>__("Address"),
                'registered_at' => '注册时间',

                'password' => __('Password'),
                'password_confirmation' => __('Confirm Password'),
            ]);

            $data = $request->only(['name', 'type_id', 'province_id', 'registered_at', 'password']);
            $data['province'] = Area::where('id', $data['province_id'])->value("name");

            if ($agency->edit($data)) {
                return redirect()->route('admin.agency.index')->with('success', __('Edit success'));
            }

            return back()->with('error', __('Edit failed'))->withInput();

        } else {
            $types = Type::where('status', 1)->get();
            $provinces = Area::where("parent_id", 0)->get();

            return backendView('agency.edit', compact('agency', 'types', 'provinces'));
        }
    }

    /**
     * 查看分类
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function view($id = null)
    {
        /**
         * @var $agency Agency
         */
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        return backendView('agency.view', compact('agency'));
    }

    /**
     * 删除分类
     * @param null $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete($id = null)
    {
        /**
         * @var $agency Agency
         */
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        try {

            $devices = $agency->devices()->get();
            Log::error($devices);

            if ( count($devices) > 0) {
                return back()->with('error', '机构下有账户或设备，不能删除');
            }

            if ($agency->delete()) {
                return back()->with('success', __('Delete success'));
            }
        } catch (\Exception $e) {
            Log::error('agency delete error:');
            Log::error($e->getMessage());
        }

        return back()->with('error', __('Delete failed'));
    }

    public function deviceadd($id = null, Request $request){
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        if ($request->isMethod("post")){
            $this->validate($request, [
                'codes' => 'required|max:255',
                'kind_id' => 'required|exists:kinds,id'
            ], [], [
                'codes' => __("Code"),
                'kind_id' => '设备类型'
            ]);

            $data = $request->only(['codes', 'kind_id']);
            $data['agency_id'] = $agency->id;

            if (true) {

                return redirect()->route('admin.agency.index')->with('success', '添加成功');
            }

            return back()->with('error', '添加失败')->withInput();
        }

        $kinds = Kind::where('status', 1)->get();
        return backendView('agency.device', compact('agency', 'kinds'));
    }

    /**
     * 机构设备列表
     * @param null $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function device($id)
    {
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        $list = $agency->agencyDevices()->paginate(config('site.other.paginate'));

        return backendView('agency.devices', compact('list'));
    }

}